package com.dbapp.garden.controller.department;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dbapp.garden.common.DataTableUtils;
import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.entity.GardenDepartment;
import com.dbapp.garden.service.GardenDepartmentService;
import com.dbapp.garden.vm.GardenDepartmentVm;
import com.dbapp.garden.vo.GardenDepartmentVo;

/**
 * 部门管理
 * 
 * @author gangzi
 *
 */
@Controller
public class GardenDepartmentController {

	@Autowired
	private GardenDepartmentService deptService;

	@GetMapping("/department")
	@PreAuthorize("hasAuthority('PERMISSION_DEPARTMENT')")
	public String toDepartmentPage(Model model) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		List<GardenDepartment> deptList = deptService.getDepartmentList(paramMap);
		model.addAttribute("departments", deptList);

		return "department/departmentlist";
	}

	@GetMapping("/departmentedit/{id}")
	@PreAuthorize("hasAuthority('PERMISSION_DEPARTMENT_EDIT')")
	public String editDepartment(@PathVariable("id") Integer id, Model model) {
		GardenDepartment department = deptService.findById(id);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		List<GardenDepartment> gardenList = deptService.getDepartmentList(paramMap);
		model.addAttribute("departments", gardenList);
		model.addAttribute("department", department);
		return "department/departmentedit";
	}

	@PostMapping("/departmentlist")
	@ResponseBody
	@PreAuthorize("hasAuthority('PERMISSION_DEPARTMENT')")
	public Map<String, ?> departmentList(HttpServletRequest request, String param) {

		Map<String, Object> paramMap = DataTableUtils.parseParam(param);
		if (paramMap == null) {
			return RenderJSON.makeMap(-1, "参数不合法！", null, "");
		}
		String sEcho = (String) paramMap.get("sEcho");
		String sSearch = (String) paramMap.get("sSearch");
		int iDisplayStart = (int) paramMap.get("iDisplayStart");
		int iDisplayLength = (int) paramMap.get("iDisplayLength");

		paramMap.clear();
		paramMap.put("search", sSearch);
		paramMap.put("start", iDisplayStart);
		paramMap.put("limit", iDisplayLength);

		List<GardenDepartment> departmentList = deptService.getDepartmentList(paramMap);
		Integer count = deptService.getDepartmentCount(paramMap);
		List<GardenDepartmentVo> departmentVoList = departmentList.stream().map(x -> {
			GardenDepartmentVo deptVo=new GardenDepartmentVo();
			try {
				BeanUtils.copyProperties(deptVo, x);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(x.getDeptParent()!=null&&x.getDeptParent()>0){
				GardenDepartment dept=deptService.findById(x.getDeptParent());
				deptVo.setDeptParentName(dept.getDeptName());
			}
			return deptVo;
		}).collect(Collectors.toList());
		return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, departmentVoList, "");
	}

	@PostMapping("/departmentadd")
	@ResponseBody
	@PreAuthorize("hasAuthority('PERMISSION_DEPARTMENT_ADD')")
	public Map<String, ?> addDepartment(HttpServletRequest request,
			@RequestBody @Valid GardenDepartmentVm departmentVm) {
		GardenDepartment department = new GardenDepartment();

		// 这里需要处理
		department.setGardenId(departmentVm.getGardenId());
		department.setDeptDesc(departmentVm.getDeptDesc());
		department.setDeptName(departmentVm.getDeptName());
		department.setDeptParent(departmentVm.getDeptParent());
		department.setDeptSort(departmentVm.getDeptSort());
		department.setCreateTime(new Date());
		department.setUpdateTime(new Date());

		Integer result = deptService.save(department);

		if (result != null && result > 0) {
			return RenderJSON.makeStandMap(1, "恭喜您，添加成功！", "ok");
		} else {
			return RenderJSON.makeStandMap(1, "对不起，添加失败！", "error");
		}

	}

	@DeleteMapping("/departmentdelete/{id}")
	@ResponseBody
	@PreAuthorize("hasAuthority('PERMISSION_DEPARTMENT_DELETE')")
	public Map<String, ?> deleteDepartment(HttpServletRequest request, @PathVariable("id") Integer id) {

		Integer result = deptService.delete(id);
		if (result != null && result > 0) {
			return RenderJSON.makeStandMap(1, "恭喜您，删除成功！", "ok");
		} else {
			return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
		}

	}

	@PostMapping("/departmentedit/{id}")
	@ResponseBody
	@PreAuthorize("hasAuthority('PERMISSION_DEPARTMENT_EDIT')")
	public Map<String, ?> editDepartment(HttpServletRequest request, @PathVariable("id") Integer id,
			@RequestBody @Valid GardenDepartmentVm departmentVm) {

		GardenDepartment department = new GardenDepartment();
		department.setId(id);
		// 这里需要处理
		department.setGardenId(departmentVm.getGardenId());
		department.setDeptDesc(departmentVm.getDeptDesc());
		department.setDeptName(departmentVm.getDeptName());
		department.setDeptParent(departmentVm.getDeptParent());
		department.setDeptSort(departmentVm.getDeptSort());

		department.setUpdateTime(new Date());

		Integer result = deptService.save(department);
		if (result != null && result > 0) {
			return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
		} else {
			return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
		}
	}
}
